package com.mrdeer.iot.rabbitmq;

import com.mrdeer.common.tools.JsonUtils;
import com.mrdeer.iot.bean.ChannelInfo;
import com.mrdeer.iot.constant.DriverContext;
import com.mrdeer.iot.handler.ChannelManagerHandler;
import com.mrdeer.iot.handler.CommandHandler;
import com.mrdeer.iot.service.IotService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Author: xie jianchu
 */
@Slf4j
@Component
public class MQDeviceEventReceiver {

    @Resource
    private IotService iotService;

    /**
     * 指令队列
     *
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    @RabbitListener(queues = "rtu_inst_queue")
    public void processMessage(Message message) throws IOException {
        String msg = new String(message.getBody());
        log.info("rtu-command:{}", msg);
        ChannelInfo channelInfo = JsonUtils.jsonStr2Obj(msg, ChannelInfo.class);
        if (channelInfo == null) {
            log.error("channelInfo is null");
            return;
        }
        //发送查询指令,message:指的是后台接收到的设备指令 command:指的是平台发送给设备的指令
        //TODO:构建指令
//        String command = InstructionBuilder.buildInstruction(channelInfo.getProtocol(), HexHelper.numToHex16(Instruction.ControlFrame.complete_machine.search));
        String command = channelInfo.getCommand();
        if (channelInfo == null) {
            log.warn("bad command:{}", channelInfo);
            return;
        }
        CommandHandler.writeCommand(channelInfo.getSn(), command);
    }

    /**
     * 刷新iot信息
     *
     * @param message
     * @throws Exception
     */
    @RabbitHandler
    @RabbitListener(queues = "rtu_refresh_queue")
    public void refreshIotInfo(Message message) throws Exception {
        String msg = new String(message.getBody());
        if (DriverContext.Global_IOT_Redis_key.equals(msg)) {
            log.info("start refresh GlobalInfo,rtu_refresh key is : {}", msg);
            boolean flag = iotService.refreshIotMapper2Global();
            if (flag) {
                ChannelManagerHandler.refreshRTUChannelInfo();
            }
        }
    }
}
